

package com.hexinfo.dmpro.sparing.controller;

import cn.hutool.core.io.file.FileAppender;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hexinfo.dmpro.common.annotation.AnonymousAccess;
import com.hexinfo.dmpro.sparing.async.AsyncTableTask;
import com.hexinfo.dmpro.sparing.dto.*;
import com.hexinfo.dmpro.sparing.model.*;
import com.hexinfo.dmpro.sparing.service.*;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


/**
 * 同步规则配置表
 *
 * @author yemw
 * @date 2023-09-08 17:45:29
 */
@RestController
@AllArgsConstructor
@RequestMapping("/api/syncruleconf" )
@Api(value = "syncruleconf", tags = "同步规则配置表管理")
public class SyncRuleConfController {

    private final SyncRuleConfService syncRuleConfService;
    private final SyncRuleConfTWOService syncRuleConfTWOService;
    private final SyncRuleConfTHREEService syncRuleConfTHREEService;
    private final SyncRuleConfFOURService syncRuleConfFOURService;
    private final AvailabilityPathService availabilityPathService;
    private final RuleToDistCPService ruleToDistCPService;
    private final DateDataService dateDataService;
    private final SyncRuleConfDatabaseService syncRuleConfDatabaseService;
    private final AsyncTableTask asyncTableTask;
    private final FailTableRetryService failTableRetryService;
    private final FailTableRetrySourceService failTableRetrySourceService;


    /**
     * 分页查询
     * @param page 分页对象
     * @param syncRuleConf 同步规则配置表
     * WrapperEnhancer.like(syncRuleConf); //自动拼接存在值sql的方法
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page" )
    public ResponseEntity<Object> getSyncRuleConfPage(Page page, SyncRuleConf syncRuleConf) {
        return ResponseEntity.ok(syncRuleConfService.queryList(page,syncRuleConf));
    }


    /**
     * 通过id查询同步规则配置表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}" )
    @AnonymousAccess
    public ResponseEntity<Object> getById(@PathVariable("id" ) String id) {
        return ResponseEntity.ok(syncRuleConfService.getById(id));
    }

    /**
     * 新增同步规则配置表
     * @param syncRuleConf 同步规则配置表
     * @return R
     */
    @ApiOperation(value = "新增同步规则配置表", notes = "新增同步规则配置表")
    @PostMapping
    @AnonymousAccess
    public ResponseEntity<Object> save(@RequestBody SyncRuleConf syncRuleConf) {
        return ResponseEntity.ok(syncRuleConfService.save(syncRuleConf));
    }

    /**
     * 修改同步规则配置表
     * @param syncRuleConf 同步规则配置表
     * @return R
     */
    @ApiOperation(value = "修改同步规则配置表", notes = "修改同步规则配置表")
    @PutMapping
    public ResponseEntity<Object> updateById(@RequestBody SyncRuleConf syncRuleConf) {
        return ResponseEntity.ok(syncRuleConfService.updateById(syncRuleConf));
    }

    /**
     * 通过id删除同步规则配置表
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除同步规则配置表", notes = "通过id删除同步规则配置表")
    @DeleteMapping("/{id}" )
    public ResponseEntity<Object> removeById(@PathVariable String id) {
        return ResponseEntity.ok(syncRuleConfService.removeById(id));
    }

    /**
     * 查询通过同步规则获取元数据表信息
     * @return
     */
    @ApiOperation(value = "查询通过同步规则获取元数据表信息", notes = "查询通过同步规则获取元数据表信息")
    @GetMapping("/qyScanMetadataWhere" )
    @AnonymousAccess
    public ResponseEntity<Object> qyScanMetadataWhere(@Param("flag") String flag,@Param("source") String source,@Param("cpWhether") String cpWhether) {
        //大表同步（只保留两年内日期分区数据）
        asyncTableTask.tableSync(source, "", "");
        return ResponseEntity.ok(syncRuleConfService.qyScanMetadataWhere(flag,source,cpWhether));
    }

    /**
     * 热备失败重跑（源、表）
     * @return
     */
    @ApiOperation(value = "热备失败重跑（源、表）", notes = "热备失败重跑（源、表）")
    @GetMapping("/failTableRetry" )
    @AnonymousAccess
    public ResponseEntity<Object> failTableRetry(@Param("source") String source) {
        return ResponseEntity.ok(failTableRetryService.failTableRetrySource(source));
    }

    @ApiOperation(value = "全库数据热备同步", notes = "全库数据热备同步")
    @GetMapping("/getSyncRuleDatabaseData" )
    @AnonymousAccess
    public ResponseEntity<Object> getSyncRuleDatabaseData(@Param("database") String database) {
        return ResponseEntity.ok(syncRuleConfDatabaseService.getSyncRuleDatabaseData(database));
    }

    @ApiOperation(value = "hive创表信息", notes = "hive创表信息")
    @GetMapping("/createTable" )
    @AnonymousAccess
    public ResponseEntity<Object> createTable(@Param("dbName") String dbName) {
        return ResponseEntity.ok(syncRuleConfDatabaseService.automatedTable(dbName,new SyncCompleteLibraryTask()));
    }



    @ApiOperation(value = "上线测试", notes = "上线测试")
    @PostMapping("/onlineTesting" )
    @AnonymousAccess
    public ResponseEntity<Object> onlineTesting(@RequestBody TbHdfsDistcpDTO dto) {
        return ResponseEntity.ok(syncRuleConfTWOService.onlineTesting(dto));
    }

    @ApiOperation(value = "特殊规则黑名单校验（时间分区）", notes = "特殊规则黑名单校验（时间分区）")
    @GetMapping("/upTableBameBlack" )
    @AnonymousAccess
    public ResponseEntity<Object> upTableBameBlack(@Param("sourceName") String sourceName) {
        return ResponseEntity.ok(syncRuleConfTWOService.upTableBameBlack(sourceName));
    }

    @ApiOperation(value = "UAT测试同步(源级)", notes = "UAT测试同步(源级)")
    @PostMapping("/handMoveSync" )
    @AnonymousAccess
    public ResponseEntity<Object> handMoveSync(@RequestBody HandMoveSyncDTO dto) {
        return ResponseEntity.ok(syncRuleConfTWOService.handMoveSync(dto));
    }

    @ApiOperation(value = "UAT同步搜索", notes = "UAT同步搜索")
    @PostMapping("/uATSyncSearch" )
    @AnonymousAccess
    public ResponseEntity<Object> uATSyncSearch(@RequestBody HandMoveSyncDTO dto) {
        return ResponseEntity.ok(syncRuleConfTWOService.uATSyncSearch(dto));
    }

    @ApiOperation(value = "UAT测试同步(库级、表级)", notes = "UAT测试同步(库级、表级)")
    @PostMapping("/uATSyncSearchDatabase" )
    @AnonymousAccess
    public ResponseEntity<Object> uATSyncSearchDatabase(@RequestBody HandMoveSyncDTO dto) {
        return ResponseEntity.ok(syncRuleConfFOURService.uATSyncSearchDatabase(dto));
    }

    @ApiOperation(value = "删除2年外的数据", notes = "删除2年外的数据")
    @GetMapping("/allSource" )
    @AnonymousAccess
    public ResponseEntity<Object> allSource() {
        return ResponseEntity.ok(syncRuleConfTHREEService.allSource());
    }

    @ApiOperation(value = "测试cdh集群nameNode活跃节点", notes = "测试cdh集群nameNode活跃节点")
    @GetMapping("/getNameNodeStatus" )
    @AnonymousAccess
    public String getNameNodeStatus() {
        return availabilityPathService.getSouAndTar();
    }

    @ApiOperation(value = "删除两年前日期分区数据", notes = "删除两年前日期分区数据")
    @GetMapping("/dropDateData" )
    @AnonymousAccess
    public boolean dropDateData(String source) {
        return ruleToDistCPService.dropDateData(source);
    }

    @ApiOperation(value = "删除两年前日期分区数据", notes = "删除两年前日期分区数据")
    @GetMapping("/dateData" )
    @AnonymousAccess
    public boolean dateData(String source) {
        FileAppender heatlog = new FileAppender(new File(System.getProperty("user.dir")+"/message/dropDate/dome.txt"), 1000, true);
        List<WhereScriptDTO> list = new ArrayList<>();
        WhereScriptDTO dto = new WhereScriptDTO();
        WhereScriptDTO dto1 = new WhereScriptDTO();
        WhereScriptDTO dto2 = new WhereScriptDTO();
        dto.setSourceDbName("ods");
        dto.setSourceTableName("yeb_asset_par_xg_3");
        dto.setSourceQueryCriteria("where cast( d_datadate as int ) BETWEEN 20031209 and 20231210");
        dto1.setSourceDbName("ods");
        dto1.setSourceTableName("yeb_asset_par_xg_3");
        dto1.setSourceQueryCriteria("where cast( bk_system as string ) = 'YEBHB' and cast( d_datadate as int ) BETWEEN 20211109 and 20231110");
        dto2.setSourceDbName("ods");
        dto2.setSourceTableName("yeb_asset_par_xg_3");
        dto2.setSourceQueryCriteria("where cast( bk_system as string ) = 'YEBCJXJB'");

        list.add(dto);
        list.add(dto1);
        list.add(dto2);
        StateDataDTO stateDataDTO = dateDataService.dropDateData(source, heatlog, list);
        return stateDataDTO.isState();
    }

    @ApiOperation(value = "大屏源级热备任务执行状态", notes = "大屏源级热备任务执行状态")
    @GetMapping("/sourceHotBackupState" )
    @AnonymousAccess
    public List<HotStandbyLogSource> sourceHotBackupState() {
        return syncRuleConfService.sourceHotBackupState();
    }

    @ApiOperation(value = "源级重试", notes = "源级重试")
    @PostMapping("/levelRetry" )
    @AnonymousAccess
    public ResponseEntity<Object> levelRetry(@RequestBody List<HotStandbyLogTable> list) {
        return ResponseEntity.ok(failTableRetrySourceService.failTableRetryTable(list));
    }

    @ApiOperation(value = "表级重试", notes = "表级重试")
    @PostMapping("/tableRetry" )
    @AnonymousAccess
    public ResponseEntity<Object> tableRetry(@RequestBody List<HotStandbyTable> hotStandbyTables) {
        return ResponseEntity.ok(asyncTableTask.failTableRetryTable(hotStandbyTables));
    }

}
